package cmsoa.filter;


import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import cmsoa.db.DBUtil;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class DBStrutsPrepareAndExecuteFilter extends
		StrutsPrepareAndExecuteFilter {
	private static final Logger logger = LoggerFactory.getLogger(DBStrutsPrepareAndExecuteFilter.class);
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setAttribute("exceptionCode", "020202");
		try{
			super.doFilter(request, response, chain);
		}finally{
			DBUtil db = (DBUtil)request.getAttribute(DBUtil.DB_SESSION_NAME);
			try {
				Exception exception = (Exception)request.getAttribute("javax.servlet.error.exception");
				String errUrl = String.valueOf(request.getAttribute("struts.view_uri"));
				if(db!=null){
					db.commit();
				}
				if(exception != null){
					db.rollback();
					logger.error("异常", exception);
				}else if(errUrl.equals("/error.jsp")){
					db.rollback();
				}
			} catch (Exception e) {
				try {
					db.rollback();
				} catch (Exception e2) {
					logger.error("异常", e2);
				}
				logger.error("异常", e);
			}
			if(db!=null){
				db.close();
				request.removeAttribute(DBUtil.DB_SESSION_NAME);
			}
		}
	}
}
